﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace neside3.func_edit
{
    /// <summary>
    /// func_edit.xaml 的交互逻辑
    /// </summary>
    public partial class panel_project : UserControl
    {
        public panel_project()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //open project
            System.Windows.Forms.FolderBrowserDialog m_Dialog = new System.Windows.Forms.FolderBrowserDialog();
            m_Dialog.Description = "请选择一个neside项目目录,他应该包含neside.json/Please select a neside project folder that who contains a file named neside.json.";
            var result = m_Dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                openproject(m_Dialog.SelectedPath);
            }

        }
        void openproject(string path)
        {
            var config = System.IO.Path.Combine(path, "neside.json");
            try
            {
                IDE.OpenProject(path);
            }
            catch (Exception err)
            {
                MessageBox.Show("错误/error:" + err.Message);
                return;
            }
            this.filetree.Items.Clear();
            updateFolder();
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //create project
            dialog_newproject dialog = new dialog_newproject();
            if (dialog.ShowDialog() == true)
            {
                openproject(dialog.ProjectPath);
            }
        }

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //build project
            bool b = await IDE.Builder.Build();

        }

        private async void Button_Click_3(object sender, RoutedEventArgs e)
        {
            //run project
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            IDE.onFileListChange += (s, sf) =>
              {
                  this.Dispatcher.Invoke(updateFolder);
              };
        }
        void updateFolder()
        {
            FillCollection(filetree.Items, new System.IO.DirectoryInfo(IDE.curProject_Folder));
        }
        class Info
        {
            public bool isDir;
            public string name;
            public string fullname;
            public override string ToString()
            {
                return isDir ? "<" + name + ">" : name.ToString();
            }
        }
        SolidColorBrush textColor = new SolidColorBrush(Color.FromRgb(0xcd, 0xcd, 0xcd));
        void FillCollection(ItemCollection coll, System.IO.DirectoryInfo dir)
        {
            Dictionary<string, string> fullnames = new Dictionary<string, string>();
            foreach (var f in dir.GetFiles())
            {
                fullnames.Add(f.FullName, f.Name);
            }
            //删除ui多出的项目
            for (var i = coll.Count - 1; i >= 0; i--)
            {
                var info = (coll[i] as TreeViewItem).Tag as Info;
                if (!info.isDir)
                {
                    if (fullnames.ContainsKey(info.fullname) == false)
                    {
                        coll.RemoveAt(i);
                    }
                    else
                    {
                        fullnames.Remove(info.fullname);
                    }
                }
            }
            //添加ui缺少的项目
            foreach (var fitem in fullnames)
            {
                TreeViewItem item = new TreeViewItem();
                item.Foreground = textColor;
                coll.Add(item);
                item.Header = fitem.Value;
                item.Tag = new Info() { isDir = false, name = fitem.Value, fullname = fitem.Key };
            }


            //检查路径
            fullnames.Clear();
            foreach (var subf in dir.GetDirectories())
            {
                fullnames.Add(subf.FullName, subf.Name);
            }
            //删除ui多出的项目
            for (var i = coll.Count - 1; i >= 0; i--)
            {
                var info = (coll[i] as TreeViewItem).Tag as Info;
                if (info.isDir)
                {
                    if (fullnames.ContainsKey(info.fullname) == false)
                    {
                        coll.RemoveAt(i);
                    }
                    else
                    {
                        fullnames.Remove(info.fullname);
                    }
                }
            }
            //添加ui缺少的项目
            foreach (var fitem in fullnames)
            {
                TreeViewItem item = new TreeViewItem();
                item.Foreground = textColor;
                coll.Add(item);
                var info = new Info() { isDir = true, name = fitem.Value, fullname = fitem.Key };
                item.Header = info.ToString();
                item.Tag = info;
            }

            //深入
            foreach (TreeViewItem item in coll)
            {
                var info = (item as TreeViewItem).Tag as Info;
                if (info.isDir)
                {
                    FillCollection(item.Items, new System.IO.DirectoryInfo(info.fullname));
                }
            }

            //resort item in tree
            List<TreeViewItem> all = new List<TreeViewItem>();
            foreach (TreeViewItem c in coll)
            {
                all.Add(c);
            }
            all.Sort((a, b) =>
            {
                var ia = a.Tag as Info;
                var ib = b.Tag as Info;

                return ia.ToString().CompareTo(ib.ToString());
            });
            coll.Clear();
            foreach (var sc in all)
            {
                coll.Add(sc);
            }

        }

        private void filetree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {//选中文件
            if (filetree.SelectedItem == null)
            {
                fileinfo.Content = null;
            }
            else
            {
                //这里没搞明白treeview的事件机制？怎么老选到上层去
                //所以是不能在这个事件内引发focus变化，否则会破坏这个选中逻辑
                //这里用begininvoke 背景线程，保证该事件结束后再执行
                Action doit = () =>
                 {

                     var info = (filetree.SelectedItem as TreeViewItem).Tag as Info;
                     if (info.isDir) return;
                     var file = IDE.Documents.OpenFile(info.fullname);
                     fileinfo.Content = file?.GetUIInfo();
                 };
                this.Dispatcher.BeginInvoke(DispatcherPriority.Background, doit);
            }
        }
    }
}
